package com.zetatech.bdp.parser.parser;

import com.zetatech.bdp.parser.processor.LineProcessor;
import com.zetatech.bdp.entity.Field;
import lombok.Cleanup;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 日志文件解析.
 * <p>
 * 通常日志文件中一行为一条记录，故一个文件对应多条记录，所以返回List
 *
 * @author cheng.cao@zetatech.com.cn
 */
public abstract class LogFileParser<T> implements FileParser<List<T>> {

    protected abstract LineProcessor<T> getLineProcessor();

    @Override
    public List<T> parse(File file, List<Field> fields) throws IOException {
        @Cleanup FileInputStream fis = new FileInputStream(file);
        @Cleanup InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
        @Cleanup BufferedReader br = new BufferedReader(isr);
        String line;
        List<T> result = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            if (line.length() == 0) {
                continue;
            }
            T t = getLineProcessor().processLine(file, line, fields);
            if (t != null) {
                result.add(t);
            }
        }
        return result;
    }
}
